﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Data;
using Maticsoft.Common;
using System.Drawing;
using LTP.Accounts.Bus;
namespace dzs.Web.instore
{
    public partial class List : Web.Admin.BasePage
    {
        dzs.BLL.instore bll = new dzs.BLL.instore();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                BindData();
                Page.DataBind();
            }
        }
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindData();
        }
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            string idlist = GetSelIDlist();
            if (idlist.Trim().Length == 0)
                return;
            bll.DeleteList(idlist);
            BindData();
        }

        #region gridView

        public DataSet BindData()
        {
            #region
            //if (!Context.User.Identity.IsAuthenticated)
            //{
            //    return;
            //}
            //AccountsPrincipal user = new AccountsPrincipal(Context.User.Identity.Name);
            //if (user.HasPermissionID(PermId_Modify))
            //{
            //    gridView.Columns[6].Visible = true;
            //}
            //if (user.HasPermissionID(PermId_Delete))
            //{
            //    gridView.Columns[7].Visible = true;
            //}
            #endregion

            DataSet ds = GetData();
            gridView.DataSource = ds;
            gridView.DataBind();
            return ds;
        }

        private DataSet GetData()
        {
            DataSet ds = new DataSet();
            StringBuilder strWhere = new StringBuilder();
            if (txtKeyword.Text.Trim() != "")
            {
                strWhere.AppendFormat(" and cast(CONVERT(varchar(12),intime, 111) as datetime)" + ddldate.SelectedValue + " '{0}'", txtKeyword.Text.Trim());
            }
            if (txtpro.Text.Trim() != "")
            {
                strWhere.AppendFormat(" and projectname like '%{0}%'", txtpro.Text.Trim());
            }
            if (txtgys.Text.Trim() != "")
            {
                strWhere.AppendFormat(" and supplier like '%{0}%'", txtgys.Text.Trim());
            }
            if (txtwl.Text.Trim() != "")
            {
                strWhere.AppendFormat(" and material like '%{0}%'", txtwl.Text.Trim());
            }
            if (Session["login"] != null)
            {
                DataSet u = (DataSet)Session["login"];

                if (u.Tables[0].Rows[0]["roles_id"].ToString() == "2")
                {
                    strWhere.AppendFormat(" and uid={0}", u.Tables[0].Rows[0]["user_id"]);
                }
            }
            ds = bll.GetinstoreByWhere(strWhere.ToString());
            return ds;
        }

        protected void gridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gridView.PageIndex = e.NewPageIndex;
            BindData();
        }

        protected void gridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            e.Row.Attributes.Add("style", "background:#FFF");
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                ImageButton bt = e.Row.FindControl("btncdel") as ImageButton;
                if (bt != null)
                {
                    //判断入库物料是否出库，如出库则不能删除
                    int mid = 0;
                    DataRowView drv = (DataRowView)e.Row.DataItem;
                    mid = int.Parse(drv["mid"].ToString());
                    dzs.BLL.out_storageList dbll = new BLL.out_storageList();
                    if (dbll.GetRecordCount("material_id=" + mid) > 0)
                        bt.Visible = false;
                }
            }
        }

        protected void gridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            //#warning 代码生成警告：请检查确认真实主键的名称和类型是否正确
            //int ID = (int)gridView.DataKeys[e.RowIndex].Value;
            //bll.Delete(ID);
            //gridView.OnBind();
        }

        private string GetSelIDlist()
        {
            string idlist = "";
            bool BxsChkd = false;
            for (int i = 0; i < gridView.Rows.Count; i++)
            {
                CheckBox ChkBxItem = (CheckBox)gridView.Rows[i].FindControl("DeleteThis");
                if (ChkBxItem != null && ChkBxItem.Checked)
                {
                    BxsChkd = true;
                    //#warning 代码生成警告：请检查确认Cells的列索引是否正确
                    if (gridView.DataKeys[i].Value != null)
                    {
                        idlist += gridView.DataKeys[i].Value.ToString() + ",";
                    }
                }
            }
            if (BxsChkd)
            {
                idlist = idlist.Substring(0, idlist.LastIndexOf(","));
            }
            return idlist;
        }

        #endregion

        protected void btnout_Click(object sender, EventArgs e)
        {
            DataSet ds = GetData();
            gridView.DataSource = ds;

            gridView.AllowPaging = false;
            gridView.Columns[0].Visible = false;
            gridView.DataBind();
            string f = DateTime.Now.Ticks.ToString();
            ExportExcel(gridView, f);
            gridView.DataSource = ds;
            gridView.AllowPaging = true;
            gridView.Columns[0].Visible = true;
            gridView.DataBind();

        }
        public override void VerifyRenderingInServerForm(Control control)
        {
            //这里没有内容。
        }

        public void ExportExcel(System.Web.UI.WebControls.WebControl objControl, string strFileName)
        {

            strFileName = System.Web.HttpUtility.UrlEncode(strFileName, System.Text.Encoding.UTF8);
            System.Web.HttpContext.Current.Response.Clear();
            System.Web.HttpContext.Current.Response.Buffer = true;
            System.Web.HttpContext.Current.Response.Charset = "gb2312";
            System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "online; filename=" + strFileName + ".xls");
            System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
            System.Web.HttpContext.Current.Response.ContentType = "application/ms-excel";

            System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("zh-CN", true);
            System.IO.StringWriter oStringWriter = new System.IO.StringWriter(myCItrad);
            System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);

            objControl.RenderControl(oHtmlTextWriter);

            objControl = null;
            System.Web.HttpContext.Current.Response.Write(oStringWriter.ToString().Replace("<td", "<td STYLE='MSO-NUMBER-FORMAT:\\@'"));
            System.Web.HttpContext.Current.Response.Buffer = false;
            System.Web.HttpContext.Current.Response.End();
        }
        public void CreateExcel(DataSet ds, string FileName)
        {
            HttpResponse resp;
            resp = Page.Response;
            resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            resp.AppendHeader("Content-Disposition", "attachment;filename=" + FileName);
            string colHeaders = "", ls_item = "";
            int i = 0;

            //定义表对象与行对像，同时用DataSet对其值进行初始化 
            DataTable dt = ds.Tables[0];
            DataRow[] myRow = dt.Select("");
            // typeid=="1"时导出为EXCEL格式文件；typeid=="2"时导出为XML格式文件 

            //取得数据表各列标题，各标题之间以\t分割，最后一个列标题后加回车符 
            colHeaders += "仓位名" + "\t";
            colHeaders += "项目编号" + "\t";
            colHeaders += "需用单位" + "\t";

            colHeaders += "项目名" + "\t";

            colHeaders += "物料名" + "\t";
            colHeaders += "项目类型" + "\t";
            colHeaders += "供应商" + "\t";
            colHeaders += "入库时间" + "\t";
            colHeaders += "入库量" + "\n";
            resp.Write(colHeaders);
            //逐行处理数据   
            foreach (DataRow row in myRow)
            {
                //在当前行中，逐列获得数据，数据之间以\t分割，结束时加回车符\n 
                for (i = 0; i < dt.Columns.Count - 1; i++)
                    ls_item += row[i].ToString() + "\t";
                ls_item += row[i].ToString() + "\n";
                //当前行数据写入HTTP输出流，并且置空ls_item以便下行数据     
                resp.Write(ls_item);
                ls_item = "";
            }


            //写缓冲区中的数据到HTTP头文件中 
            resp.End();


        }

        protected void gridView_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "delc")
            {
                //删除入库记录，同时对库存进行修改
                int index = ((GridViewRow)((ImageButton)e.CommandSource).NamingContainer).RowIndex;
                int id = int.Parse(gridView.DataKeys[index].Value.ToString());
                dzs.Model.instore m= bll.GetModel(id);
                            
                int mid = m.mid.Value;
                int spid = m.spid.Value;
                decimal nums = m.innum.Value;
                dzs.BLL.inventory bin = new BLL.inventory();
                if (bin.Updatenums(mid, spid, nums))
                {
                    //改变入库物料的状态，让物料重新可以入库
                    //修改物料状态
                    dzs.BLL.materialinfo bm = new BLL.materialinfo();
                    bm.Updatestatus(mid,0);
                   
                    if (bll.Delete(id))
                    {
                        int did = bm.Getdid(mid);
                        if (did != 0)
                        {
                            Maticsoft.BLL.monthSupplayPlan mb = new Maticsoft.BLL.monthSupplayPlan();
                            //mb.Updatedate(2, id);
                            mb.Updateresult(id);
                        }
                        BindData();
                    }
                    else
                    {
                        MessageBox.Show(this, "库存量不够或其它原因没有删除成功！");
                    }
                }

               
            }
        }


    }
}
